package com.lb.shopguide.manager.service.update;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioAttributes;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.widget.RemoteViews;

import com.blankj.utilcode.util.AppUtils;
import com.lb.shopguide.R;
import com.lb.shopguide.config.AppConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.ui.activity.GuideMainActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * download service
 *
 * @author zk
 * @created 2014年11月18日 下午3:02:36
 * TOD
 */
public class DownloadApkService extends Service {


    private static final int NOTIFY_ID = 0;
    private final String tag = "download";
    private int progress;
    private NotificationManager mNotificationManager;
    private boolean canceled;

    private String downloadUrl;

    private String mTitle = "正在下载%s";

    private String saveFileName = AppConfigManager.DIR_APK;

    private ICallbackResult callback;

    private DownloadBinder binder;

    private boolean serviceIsDestroy = false;

    private Context mContext = this;

    private Thread downLoadThread;

    private Notification mNotification;


    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:// 下载完毕
//                    mNotificationManager.cancel(NOTIFY_ID);
                    installApk();
                    break;
                case 2:// 取消通知
                    mNotificationManager.cancel(NOTIFY_ID);
                    break;
                case 1:
                    NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, AppConstant.CHANNEL_BOSS_NOTIFICATION);
                    builder.setContentTitle("正在下载中").setContentText("身边店导购端正在下载中").setSmallIcon(R.drawable.logo);
                    builder.setProgress(0, 0, true);
                    builder.setAutoCancel(false);
                    int rate = msg.arg1;
                    if (rate < 100) {
                        builder.setContentText(mTitle + "(" + rate + "%" + ")").setProgress(100, rate, false);
                        mNotification = builder.build();
                        mNotification.flags = Notification.FLAG_NO_CLEAR;
                    } else {
                        // 更新参数,注意flags要使用FLAG_UPDATE_CURRENT
                        PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, new Intent(), PendingIntent.FLAG_CANCEL_CURRENT);
                        builder.setContentIntent(contentIntent).setContentTitle("下载完成").setContentText("文件已下载完毕").setProgress(0, 0, false);
                        mNotification = builder.build();
                        mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
                        serviceIsDestroy = true;
                        stopSelf();// 停掉服务自身
                    }
                    adapterAndroidOreo();
                    mNotificationManager.notify(NOTIFY_ID, mNotification);
                    break;
            }
        }
    };
    private Runnable mDownApkRunnable = new Runnable() {
        @Override
        public void run() {
            File file = new File(AppConfigManager.DIR_APK);
            if (!file.exists()) {
                file.mkdirs();
            }
            String apkFile = saveFileName;
            File saveFile = new File(apkFile);
            try {
                downloadUpdateFile(downloadUrl, saveFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        downloadUrl = intent.getStringExtra(AppConstant.DOWNLOAD_URL);
        String version = intent.getStringExtra(AppConstant.DOWNLOAD_VERSION);
        saveFileName = saveFileName + File.separator + version;
        mTitle = "正在下载" + getString(R.string.app_name);
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        binder = new DownloadBinder();
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        stopForeground(true);// 这个不确定是否有作用
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void startDownload() {
        canceled = false;
        downloadApk();
    }

    private void adapterAndroidOreo() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(AppConstant.CHANNEL_BOSS_NOTIFICATION, "身边店下载", NotificationManager.IMPORTANCE_DEFAULT);
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
                    .build();
            channel.setSound(null, audioAttributes);
            mNotificationManager.createNotificationChannel(channel);
        }
    }

    /**
     * 创建通知
     */
    private void setUpNotification() {
        //图标暂无
        int icon = R.drawable.logo;
        CharSequence tickerText = "准备下载身边店导购端";
        long when = System.currentTimeMillis();
        mNotification = new Notification(icon, tickerText, when);
        // 放置在"正在运行"栏目中
        mNotification.flags = Notification.FLAG_ONGOING_EVENT;

        RemoteViews contentView = new RemoteViews(getPackageName(),
                R.layout.download_notification_show);
        contentView.setTextViewText(R.id.tv_download_state, mTitle);
        // 指定个性化视图
        mNotification.contentView = contentView;

        Intent intent = new Intent(this, GuideMainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);

        // 指定内容意图
        mNotification.contentIntent = contentIntent;
        mNotificationManager.notify(NOTIFY_ID, mNotification);
    }

    private void downloadApk() {
        downLoadThread = new Thread(mDownApkRunnable);
        downLoadThread.start();
    }

    /**
     * 安装apk
     */
    private void installApk() {
        File apkFile = new File(saveFileName);
        if (!apkFile.exists()) {
            return;
        }
        AppUtils.installApp(apkFile, "com.lb.shopguide.fileprovider");
    }

    public long downloadUpdateFile(String downloadUrl, File saveFile)
            throws Exception {
        int downloadCount = 0;
        int currentSize = 0;
        long totalSize = 0;
        int updateTotalSize = 0;

        HttpURLConnection httpConnection = null;
        InputStream is = null;
        FileOutputStream fos = null;

        try {
            URL url = new URL(downloadUrl);
            httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection
                    .setRequestProperty("User-Agent", "PacificHttpClient");
            if (currentSize > 0) {
                httpConnection.setRequestProperty("RANGE", "bytes="
                        + currentSize + "-");
            }
            httpConnection.setConnectTimeout(10000);
            httpConnection.setReadTimeout(20000);
            updateTotalSize = httpConnection.getContentLength();
            if (httpConnection.getResponseCode() == 404) {
                throw new Exception("fail!");
            }
            is = httpConnection.getInputStream();
            fos = new FileOutputStream(saveFile, false);
            byte buffer[] = new byte[1024];
            int readsize = 0;
            while ((readsize = is.read(buffer)) > 0) {
                fos.write(buffer, 0, readsize);
                totalSize += readsize;
                // 为了防止频繁的通知导致应用吃紧，百分比增加10才通知一次
                if ((downloadCount == 0)
                        || (int) (totalSize * 100 / updateTotalSize) - 5 >= downloadCount) {
                    downloadCount += 5;
                    // 更新进度
                    Message msg = mHandler.obtainMessage();
                    msg.what = 1;
                    msg.arg1 = downloadCount;
                    mHandler.sendMessage(msg);
                    if (callback != null)
                        callback.OnBackResult(progress);
                }
            }
            // 下载完成通知安装
            mHandler.sendEmptyMessage(0);
            // 下载完了，cancelled也要设置
            canceled = true;
        } finally {
            if (httpConnection != null) {
                httpConnection.disconnect();
            }
            if (is != null) {
                is.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
        return totalSize;
    }

    public class DownloadBinder extends Binder {
        public void start() {
            if (downLoadThread == null || !downLoadThread.isAlive()) {
                progress = 0;
                setUpNotification();
                new Thread() {
                    public void run() {
                        // 下载
                        startDownload();
                    }
                }.start();
            }
        }

        public void cancel() {
            canceled = true;
        }

        public int getProgress() {
            return progress;
        }

        public boolean isCanceled() {
            return canceled;
        }

        public boolean serviceIsDestroy() {
            return serviceIsDestroy;
        }

        public void cancelNotification() {
            mHandler.sendEmptyMessage(2);
        }

        public void addCallback(ICallbackResult callback) {
            DownloadApkService.this.callback = callback;
        }
    }
}
